package servlet;


import mongo.UserAccount;
import mongo.SchoolYearSemester;
import org.bson.Document;
import org.bson.types.ObjectId;

import com.mongodb.client.MongoCursor;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@WebServlet(description = "loginProcess", urlPatterns = { "/login" })
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String username=request.getParameter("username");
        String password=request.getParameter("password");
        boolean isremember=Boolean.parseBoolean(request.getParameter("isremember"));
        
        UserAccount userAccount = new UserAccount();
        SchoolYearSemester schoolYearSemester = new SchoolYearSemester();
        String loginUrl = "";
        
        //获取session对象
        HttpSession session = request.getSession();
    
        try {
        	Document result = userAccount.verifyLogin(username, password);
        	Boolean loginResult = result.getBoolean("login");
            if(loginResult&&result.getBoolean("isopen")){ 
            	if(isremember) {
            		// 记住密码
	            	username = URLEncoder.encode(username, "UTF-8");	//编码
	    			Cookie c_name = new Cookie("username",username);
	    			Cookie c_pwd = new Cookie("password",password);
	    			response.addCookie(c_name); //将指定的 Cookie 添加到响应中
	    			response.addCookie(c_pwd);
            	}
            	else {
            		//删除cookie
            		Cookie[] cookies = request.getCookies();
            		if(cookies!=null&&cookies.length>1) {
	            		for(Cookie c : cookies){  
	            		    c.setMaxAge(0);  
	            		    response.addCookie(c);
	            		}  
            		}
            	}
            	session.setAttribute("result", result);
            	session.setAttribute("yearSemester", schoolYearSemester.get());
            	String type = result.getString("type");
            	if(type.equals("a")){
            		loginUrl = "manager/userManage/userManageServlet?method=list&type=t";
            	}else if(type.equals("s")){
            		loginUrl = "student/studentInfo.jsp";
            	}else{
            		loginUrl = "teacher/teacherInfo.jsp";
            	}
            }else{
            	if(result.getBoolean("isopen")==null || result.getBoolean("isopen")){
	            	session.setAttribute("error", "用户名或密码错误！请重新输入！");
            	}else{
            		session.setAttribute("error", "账号被禁用，请联系管理员解禁！");
            	}
            	loginUrl = "login.jsp";
            }  
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            session.setAttribute("error", "账号异常！登录失败！");
            loginUrl = "login.jsp";
        }
       
        response.sendRedirect(loginUrl);
        //request.getRequestDispatcher(loginUrl).forward(request, response);
    }
}